<?php
set_include_path("../include;include");
require_once '/util/globals.php';
require_once 'Database.php';
require_once '/model/Member.php';
require_once '/model/Group.php';

/**
 * database access class for Member
 *
 * @author Thomas Crepain <contact@thomascrepain.be>
 */
class MemberDAO
{
        const TABLENAME = 'member';

	/**
	 *
	 *
	 * @var Database
	 */
	private $db;

	/**
	 * Contains the group cache
	 *
	 * @var array
	 */
	private $memberCache = array();

	/**
	 * unique instance of this class
	 * Singleton pattern
	 *
	 * @var Database
	 */
	private static $uniqueInstance;


	/**
	 * constructs the DAO
	 */
	private function __construct()
	{
		// get database
                $this->db = Database::getInstance();
	}

	/**
	 * gets instance of database
	 *
	 * @return MemberDAO
	 */
	public static function getInstance()
	{
		if(!isset(self::$uniqueInstance))
		{
			self::$uniqueInstance = new self();
		}

		return self::$uniqueInstance;
	}

	/**
	 * Returns the firstname
	 *
	 * @return String
	 */
	public function getFirstnameByMemberId(integer $memberId)
	{
		// build cache
		$this->buildCache($memberId);

		return $this->memberCache[$memberId]['firstname'];
	}


	/**
	 * Returns the lastname
	 *
	 * @return String
	 */
	public function getLastnameByMemberId(integer $memberId)
	{
		// build cache
		$this->buildCache($memberId);

		return $this->memberCache[$memberId]['lastname'];
	}

        /**
	 * Returns the group
	 *
	 * @return integer
	 */
	public function getGroupIdByMemberId(integer $memberId)
	{
		// build cache
		$this->buildCache($memberId);

		return (int) $this->memberCache[$memberId]['group_id'];
	}

        /**
         * Returns all members in the database
         *
         * @return Array of members
         */
        public function getAllMembers(){
            $members = array();

            $records = $this->db->getRecords("SELECT m.member_id, m.firstname, m.lastname, m.group_id
                                                FROM ".self::TABLENAME." AS m
                                                ORDER BY m.lastname ASC",
                                                array());

            foreach ($records as $record) {
                // put records in cache
                $this->memberCache[(integer) $record['member_id']] = $record;

                // make objects
                $member = Member::createNew($record['firstname'], $record['lastname'], Group::loadGroup((integer)  $record['group_id']));
                $members[] = $member;
            }

            return $members;
        }


	/**
	 * Build the cache for the memberId if needed
	 *
	 * @param integer	$memberId
	 */
	private function buildCache(integer $memberId)
	{
		// if cache is not build
		if(!isset($this->memberCache[$memberId]))
		{
                    // fill cache with this member
                    $this->memberCache[$memberId] = $this->db->getRecord("SELECT m.member_id, m.firstname, m.lastname, m.group_id
                                                                            FROM ".self::TABLENAME." AS m
                                                                            WHERE m.member_id = ?",
                                                                            array($memberId));
		}
	}


        /**
         * Saves the given member in the database
         *
         * @param Member $member
         * @return integer $id  id in database
         */
        public function save(Member $member){
            $id = 0;

            // is this a new member?
            if(is_null($member->getId())){
                $id = $this->db->insert(self::TABLENAME, array(
                        'firstname' => $member->getFirstname(),
                        'lastname' => $member->getLastname(),
                        'group_id' => $member->getGroup()->getId()));
            } else {
                $id = $member->getId();

                $this->db->update(self::TABLENAME, array(
                        'firstname' => $member->getFirstname(),
                        'lastname' => $member->getLastname(),
                        'group_id' => $member->getGroup()->getId()));
            }

            return $id;
        }
        
        /** Sifaka's addition */
        public function getTak(string $firstname, string $lastname) {
        	$result = $this->db->getRecord(
        	"SELECT g.name FROM ".self::TABLENAME." AS m INNER JOIN ".GroupDAO::TABLENAME." AS g 
        	ON m.group_id = g.group_id 
        	WHERE m.firstname = ? AND m.lastname = ?", 
        	array($firstname,$lastname));
        	
        	if (isset($result['name'])) {
        		return $result['name'];
        	} else {
        		return null;
        	}
        }
}

?>